import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:yuan_hang_app/bean/dict_entity.dart';
import 'package:yuan_hang_app/bean/exterior_entity.dart';
import 'package:yuan_hang_app/bean/interior_entity.dart';
import 'package:yuan_hang_app/bean/model_entity.dart';
import 'package:yuan_hang_app/bean/version_entity.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/jmessage_helper.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

import '../bean/user.dart';

class CommonReqUtils {
  static const leaderSource = "leaderSource"; //线索来源1009
  static const intentRange = "intentRange"; //意向级别2430
  static const leadsStatus = "leadsStatusList"; //线索状态1016
  static const driveMethod = "driveMethod"; //试驾方式2465
  static const driveType = "driveType"; //试驾类型2461
  static const sex = "sex"; //性别1002
  static const yesOrNo = "yesOrNo"; //是否1004
  static const customerType = "customerType"; //客户类型2428
  static const cardType = "cardType"; //证件类型2431
  static const activityStatus = "activityStatus"; //市场活动状态1014
  static const buyCarWay = "buyCarWay"; //购车方式1024
  static const payCarWay = "payCarWay"; //支付方式2711
  static const followUpWay = "followUpWay"; //跟进方式2442
  static const followUpResult = "followUpResult"; //跟进结果1910
  static const defeatResult = "defeatResult"; //战败原因1911
  static const invalidityReason = "invalidityReason"; //无效原因1912
  static const contactType = "contactType"; //接触类型1013
  static const driveStatus = "driveStatus"; //试驾状态1018
  static const storeType = "storeType"; //门店类型1005
  static const bookStatus = "bookStatus"; //预约状态1021
  static const appointType = "appointType"; //预约类型1022
  static const orderStatus = "orderStatus"; //订单状态1020
  static const directStoreStatus = "directStoreStatus"; //直营店类型1019
  static const activityLevel = "activityLevel"; //活动等级1017
  static const numOfInstallments = "numOfInstallments"; //分期数2710
  static const financialInstitution = "financialInstitution"; //归属金融2468
  static const salesman = "salesman"; //销售顾问
  static const carType = "carType"; //意向车型
  static const storeOrderStatus = "storeOrderStatus"; //订单状态
  static const storeCarStatus = "storeCarStatus"; //车辆状态
  static const storeMatchCarStatus = "storeMatchCarStatus"; //配车状态
  static const storeLockStatus = "storeLockStatus"; //锁车状态

  static Future<void> getDictList() async {
    saveModelList();
    return getDictByTypes(
            "1009,2430,1016,2465,2461,1002,1004,2428,2431,1014,2711,1024,2442,1910,1911,1912,1013,1018,1005,1021,1020,1022,1019,1017,2710,2468,4003,4009,4011,4014")
        .then((value) {
      SpUtil.putObjectList(leaderSource,
          DictEntity.exchangeLabelList(filterListByType(value, 1009)));
      SpUtil.putObjectList(intentRange,
          DictEntity.exchangeLabelList(filterListByType(value, 2430)));
      SpUtil.putObjectList(leadsStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 1016)));
      SpUtil.putObjectList(driveMethod,
          DictEntity.exchangeLabelList(filterListByType(value, 2465)));
      SpUtil.putObjectList(driveType,
          DictEntity.exchangeLabelList(filterListByType(value, 2461)));
      SpUtil.putObjectList(
          sex, DictEntity.exchangeLabelList(filterListByType(value, 1002)));
      SpUtil.putObjectList(
          yesOrNo, DictEntity.exchangeLabelList(filterListByType(value, 1004)));
      SpUtil.putObjectList(customerType,
          DictEntity.exchangeLabelList(filterListByType(value, 2428)));
      SpUtil.putObjectList(cardType,
          DictEntity.exchangeLabelList(filterListByType(value, 2431)));
      SpUtil.putObjectList(activityStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 1014)));
      SpUtil.putObjectList(buyCarWay,
          DictEntity.exchangeLabelList(filterListByType(value, 1024)));
      SpUtil.putObjectList(payCarWay,
          DictEntity.exchangeLabelList(filterListByType(value, 2711)));
      SpUtil.putObjectList(followUpWay,
          DictEntity.exchangeLabelList(filterListByType(value, 2442)));
      SpUtil.putObjectList(followUpResult,
          DictEntity.exchangeLabelList(filterListByType(value, 1910)));
      SpUtil.putObjectList(defeatResult,
          DictEntity.exchangeLabelList(filterListByType(value, 1911)));
      SpUtil.putObjectList(invalidityReason,
          DictEntity.exchangeLabelList(filterListByType(value, 1912)));
      SpUtil.putObjectList(contactType,
          DictEntity.exchangeLabelList(filterListByType(value, 1013)));
      SpUtil.putObjectList(driveStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 1018)));
      SpUtil.putObjectList(storeType,
          DictEntity.exchangeLabelList(filterListByType(value, 1005)));
      SpUtil.putObjectList(bookStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 1021)));
      SpUtil.putObjectList(orderStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 1020)));
      SpUtil.putObjectList(appointType,
          DictEntity.exchangeLabelList(filterListByType(value, 1022)));
      SpUtil.putObjectList(directStoreStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 1019)));
      SpUtil.putObjectList(activityLevel,
          DictEntity.exchangeLabelList(filterListByType(value, 1017)));
      SpUtil.putObjectList(numOfInstallments,
          DictEntity.exchangeLabelList(filterListByType(value, 2710)));
      SpUtil.putObjectList(financialInstitution,
          DictEntity.exchangeLabelList(filterListByType(value, 2468)));
      SpUtil.putObjectList(storeCarStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 4009)));
      SpUtil.putObjectList(storeOrderStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 4003)));
      SpUtil.putObjectList(storeMatchCarStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 4011)));
      SpUtil.putObjectList(storeLockStatus,
          DictEntity.exchangeLabelList(filterListByType(value, 4014)));

    });
  }

  static List<DictEntity> filterListByType(List<DictEntity> list, type) {
    return list.where((item) => item.type == type).toList();
  }

  ///通过key获取缓存的字典等数据列表
  static List<Map> getLabelListByKey(String key) {
    return SpUtil.getObjectList(key) ?? [];
  }

  ///获取类型列表
  static Future getDictByType(type) async {
    return HttpUtils()
        .get<List<DictEntity>>("${Api.getCodeByType}?type=$type")
        .then((value) {
      return value.data;
    });
  }

  ///获取类型列表
  static Future getDictByTypes(types) async {
    return HttpUtils()
        .get<List<DictEntity>>("${Api.getCodeListByTypes}?types=$types")
        .then((value) {
      return value.data;
    });
  }

  static void saveModelList() {
    getModelList().then((value) {
      SpUtil.putObjectList(carType, ModelEntity.exchangeLabelList(value));
    });
  }

  ///查询本组织下的销售经理
  static void getSalesmanList() {
    ///判断当前登录人是否是店长角色，如果是店长执行下面的请求，如果不是店长是顾问则无需请求直接设置当前登陆人
    User user = WConstant().userInfo;
    bool isAdviser = user.roleCode == "DZ";
    if (isAdviser) {
      ///   Map<String, dynamic>? queryParams = ;
      HttpUtils().post(Api.getSalesmanList2, data: {
        "needFollowTimes": false,
        "nameOrPhone": null,
      }).then((value) {
        if (value.data != null) {
          List list = value.data
              .map((item) => {
                    "label": item["userName"],
                    "value": item["userId"].toString()
                  })
              .toList();
          SpUtil.putObjectList(salesman, List<Map>.from(list));
        }
      });
    } else {
      List<Map<String, dynamic>> myList = [];
      var itemDict = {
        "label": user.employeeName,
        "value": user.userId.toString()
      };
      myList.add(itemDict);
      SpUtil.putObjectList(salesman, myList);
    }
  }

  ///获取标签列表
  static Future<List<Map>> getTagList() async {
    return HttpUtils()
        .get("${Api.getTagList}?shopId=${WConstant().userInfo.shopId}")
        .then((value) {
      if (value.data != null) {
        List list = value.data
            .map((item) =>
                {"tagName": item["tag_name"], "id": item["id"].toString()})
            .toList();
        return List<Map>.from(list);
      } else {
        return [];
      }
    });
  }

  ///获取大区列表
  static Future<List<Map>> getRegionList() async {
    return HttpUtils()
        .get(Api.getRegion)
        .then((value) {
      if (value.data != null) {
        List list = value.data
            .map((item) =>
        {"value": item["regionId"].toString(), "label": item["regionName"]})
            .toList();
        return List<Map>.from(list);
      } else {
        return [];
      }
    });
  }

  ///获取省
  static Future<List<Map>> getProvinceList() async {
    return HttpUtils().get(Api.getProvinceOrCity).then((value) {
      if (value.resultCode == 200) {
        return List<Map>.from(value.data);
      } else {
        return [];
      }
    });
  }

  ///获取市
  static Future<List<Map>> getCityList(provinceId) async {
    return HttpUtils().get("${Api.getProvinceOrCity}?provinceId=$provinceId").then((value) {
      if (value.resultCode == 200) {
        return List<Map>.from(value.data);
      } else {
        return [];
      }
    });
  }



  ///查询所有车辆车型列表
  static Future getModelList() async {
    return HttpUtils().get<List<ModelEntity>>(Api.getModelList).then((value) {
      return value.data;
    });
  }

  ///获取车辆版本列表
  static Future getVersionByModeId(modelId) async {
    return HttpUtils()
        .get<List<VersionEntity>>(
      "${Api.getVersionModelId}?modelId=$modelId",
    )
        .then((value) {
      return value.data;
    });
  }

  ///获取外观列表
  static Future getExteriorModelById(modelId) async {
    return HttpUtils()
        .get<List<ExteriorEntity>>(
      "${Api.getExteriorModelById}?modelId=$modelId",
    )
        .then((value) {
      return value.data;
    });
  }

  ///获取内饰列表
  static Future getInteriorModelById(exteriorId) async {
    return HttpUtils()
        .get<List<InteriorEntity>>(
      "${Api.getInteriorModelById}?exteriorId=$exteriorId",
    )
        .then((value) {
      return value.data;
    });
  }

  static String exchangeCodeToName(key, code) {
    var list = getLabelListByKey(key);
    for (int i = 0; i < list.length; i++) {
      Map item = list[i];
      if (item["value"] == code.toString()) {
        return item["label"];
      }
    }
    return "";
  }

  static String? exchangeCodeToName2(list, code) {
    for (int i = 0; i < list.length; i++) {
      Map item = list[i];
      if (item["value"] == code.toString()) {
        return item["label"];
      }
    }
  }

  static void loginOut() {
    // String token = SpUtil.getString(WConstant.token) ?? "";
    // Map<String, dynamic> params = {
    //   "jwt": token,
    // };
    //
    // HttpUtils().get(Api.loginOut, queryParams: params).then((value) {
    //
    // }).catchError((e) {
    //
    // });
    Toast.showLoading();
    String username = SpUtil.getString(WConstant.username) ?? "";
    String password = SpUtil.getString(WConstant.password) ?? "";
    JmessageHelper.removeAlias();
    WConstant.cleanList();
    SpUtil.clear()?.then((value) {
      Toast.dismissLoading();
      SpUtil.putString(WConstant.username, username);
      SpUtil.putString(WConstant.password, password);
      WConstant.navigatorKey.currentState?.pushNamed("/loginPage");
    });
  }
}
